package com.yeskery.nut.core;

import com.yeskery.nut.util.StringUtils;

import java.util.Objects;

/**
 * 路径对象
 * @author sprout
 * 2022-05-12 12:28
 */
public class Path {

    /** 路径 */
    private final String path;

    /**
     * 构建一个路径
     * @param path 路径
     */
    public Path(String path) {
        if (path == null) {
            throw new IllegalArgumentException("Path must not be null.");
        }
        int index = path.indexOf('?');
        if (index == 0) {
            path = "";
        } else if (index > 1) {
            path = path.substring(0, index);
        }
        path = path.replaceAll("[/]{2,}", "/");
        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("Path must not be empty.");
        }

        this.path = path;
    }

    /**
     * 获取路径
     * @return 路径
     */
    public String getPath() {
        return path;
    }

    /**
     * 比较两个路径是否匹配
     * @param path 比较的路径
     * @return 两个路径是否匹配
     */
    public boolean match(String path) {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        return new Path(path).path.startsWith(this.path);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null) {
            return false;
        }
        if (Path.class.isAssignableFrom(o.getClass())) {
            Path path1 = (Path) o;
            return path.equals(path1.path);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(path);
    }
}
